package com.beiing.tianshuai.tianshuai.mine.ui;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.FeedBackBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.FeedBackPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.FeedBackViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class FeedBackActivity extends BaseActivity implements FeedBackViewImpl {

    public static final int                     PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private static final String                 TAG = "FeedBackActivity";
    private Unbinder                            mUnbinder;
    private FeedBackPresenter                   mPresenter;
    private Context                             mContext;
    private String                              mPhotoPath;
    private String                              mOutFilePath;

    @BindView(R.id.iv_feedback_pic)
    ImageView mIvFeedbackPic;
    @BindView(R.id.toolbar_navigation)
    ImageView mToolbarNavigation;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.ll_submit_feedback)
    LinearLayout mBtnSubmitFeedback;
    @BindView(R.id.rg_feedback_type)
    RadioGroup mRgFeedbackType;
    @BindView(R.id.edit_feedback_content)
    EditText mEditFeedbackContent;
    @BindView(R.id.edit_text_length)
    TextView mEditTextLength;
    @BindView(R.id.btn_delete)
    Button mBtnDelete;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_feed_back;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initListener();
        initPresenter();
    }

    private void initListener() {
        // 删除图片
        mBtnDelete.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!TextUtils.isEmpty(mOutFilePath)) {
                    mOutFilePath = "";
                    mIvFeedbackPic.setImageResource(R.mipmap.icon_camera_solid);
                    mIvFeedbackPic.setBackgroundColor(ContextCompat.getColor(mContext, R.color.gallery_blue));
                    mBtnDelete.setVisibility(View.GONE);
                }
            }
        });

        // 内容
        mEditFeedbackContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int before, int subtract, int add) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int length = editable.length();
                mEditTextLength.setText(MessageFormat.format("{0}/180", length));
                if (length == 180 || length < 10) {
                    mEditTextLength.setTextColor(ContextCompat.getColor(mContext, R.color.textColorRed));
                } else {
                    mEditTextLength.setTextColor(ContextCompat.getColor(mContext, R.color.textColorGrayDark));
                }
            }
        });

        // 返回
        mToolbarNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 提交反馈
        mBtnSubmitFeedback.setOnClickListener(new BGAOnNoDoubleClickListener() {

            private String mContent;

            @Override
            public void onNoDoubleClick(View view) {
                String uid = UserInfoBean.getUid(mContext);
                String name = UserInfoBean.getNickName(mContext);
                int checkedRadioButtonId = mRgFeedbackType.getCheckedRadioButtonId();
                RadioButton radioChecked = (RadioButton) findViewById(checkedRadioButtonId);
                String type = radioChecked.getText().toString();
                mContent = mEditFeedbackContent.getText().toString();
                if (TextUtils.isEmpty(mContent)) {
                    showShortText("请输入反馈内容");
                    return;
                } else {
                    if (mContent.length() < 10) {
                        showShortText("请至少输入10个字");
                        return;
                    }
                }
                if (!TextUtils.isEmpty(mOutFilePath)) {
                    mPresenter.getFeedBackResult(uid, mContent, name, type, new File(mOutFilePath));
                } else {
                    mPresenter.getFeedBackWithoutPicResult(uid, mContent, name, type);
                }
            }
        });

        // 选择图片
        mIvFeedbackPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkSelfPermission();
            }
        });
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(FeedBackActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(FeedBackActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            RequestOptions options = new RequestOptions()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .centerCrop();
                            Glide.with(mContext.getApplicationContext())
                                    .load(outfile)
                                    .apply(options)
                                    .into(mIvFeedbackPic);
                            mIvFeedbackPic.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
                            mOutFilePath = outfile;
                            mBtnDelete.setVisibility(View.VISIBLE);
                            File file = new File(outfile);
                            long length = file.length();
                            LogUtils.i("File length : " + length, TAG);
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(FeedBackActivity.this);
    }

    private void initPresenter() {
        mPresenter = new FeedBackPresenter(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在上传，请稍后...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(FeedBackBean bean) {
        if (bean.getCode() == 200) {
            showLongText("提交成功，感谢您的反馈！");
            LogUtils.e(bean.getData().getNumber(), TAG);
            finish();
        } else {
            LogUtils.e(bean.getData().toString(), TAG);
            showLongText("抱歉，提交失败！");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showLongText("网络异常");
    }
}
